<template>
  <div class="login-container">
    <div class="login-container-banner">
      <div class="container-banner-left"></div>
      <div class="container-banner-right">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <div class="title-container">
            <img
              class="title-container-left"
              src="../../assets/images/login-logo.png"
            />
            <img
              class="title-container-right"
              src="../../assets/images/login-title.png"
            />
          </div>
          <h3>欢迎登录！</h3>
          <p class="sub-title">用户名</p>
          <el-form-item prop="username" class="login-info">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="请输入登录账号"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>
          <p class="sub-title">密码</p>
          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="password" class="login-info">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="请输入密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>
          </el-tooltip>
          <p class="sub-title">验证码</p>
          <el-form-item prop="captcha" class="login-info">
            <div class="inputCodeBox">
              <input
                type="text"
                placeholder="请输入验证码"
                @keyup.enter="handleLogin"
                v-model="loginForm.captcha"
              />
              <div class="inputLine"></div>
              <img
                :src="codeImg"
                @click="refreshCode"
                class="form-code"
                alt=""
              />
            </div>
          </el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            class="login-btn"
            @click.native.prevent="handleLogin"
            >登录</el-button
          >
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import SocialSign from "./components/SocialSignin";
import { getCodeImg } from "@/api/user";

export default {
  name: "Login",
  components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      // if (!validUsername(value)) {
      //   callback(new Error('Please enter the correct user name'))
      // } else {
      callback();
      // }
    };
    const validatePassword = (rule, value, callback) => {
      // if (value.length < 6) {
      //   callback(new Error('The password can not be less than 6 digits'))
      // } else {
      callback();
      // }
    };
    return {
      loginForm: {
        // username: 'admin',
        // password: 'admin@123',
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        captcha: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      codeImg: "",
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
    this.getCapture();
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    getCapture() {
      this.loginForm.uuid = this.randomString(32);
      getCodeImg(this.loginForm.uuid).then((res) => {
        this.codeImg = "data:image/jpeg;base64," + res.img;
      });
    },
    refreshCode() {
      this.loginForm.uuid = this.randomString(32);
      getCodeImg(this.loginForm.uuid).then((res) => {
        this.codeImg = "data:image/jpeg;base64," + res.img;
      });
    },
    randomString(length) {
      var str =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      var result = "";
      for (var i = length; i > 0; --i)
        result += str[Math.floor(Math.random() * str.length)];
      return result;
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      // this.$refs.loginForm.validate(valid => {
      // if (valid) {
      this.loading = true;
      this.$store
        .dispatch("user/login", this.loginForm)
        .then(() => {
          this.$router.push({
            path: "/",
            query: this.otherQuery,
          });
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  .login-container-banner {
    width: 100%;
    height: 100vh;
    border-radius: 18px;
    background-color: #fff;
    box-shadow: 0px 6px 20px 0px rgba(0, 63, 126, 0.11);
    display: flex;
    .container-banner-left {
      width: 75%;
      height: auto;
      background-image: url("../../assets/images/login-banner.png");
      background-repeat: no-repeat;
      background-size: cover;
      position: relative;
      .xiushi {
        position: absolute;
        left: 80px;
        top: 180px;
        max-width: 750px;
        img {
          width: 100%;
        }
      }
    }
    .container-banner-right {
      width: 40%;
      margin-top: 8%;
      h3 {
        margin-left: 15%;
        margin-top: 25px;
        font-size: 30px;
      }
      .sub-title {
        margin-left: 15%;
        margin: 10px 0 10px 15%;
        font-size: 16px;
        color: #505a69;
      }
    }
  }
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #889aa4;
      height: 47px;
      caret-color: #889aa4;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #f2f4f9 inset !important;
        -webkit-text-fill-color: #000 !important;
        -webkit-box-shadow: 0 0 0px 1000px #f2f4f9 inset !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  // background-image: url("../../assets/images/login-bg.png");
  background-repeat: no-repeat;
  background-size: cover;
  overflow: hidden;
  position: relative;

  .login-form {
    // position: absolute;
    // top: 25%;
    // right: 310px;
    // width: 460px;
    // height: 600px;
    // box-shadow: 0px 6px 20px 0px rgba(0, 63, 126, 0.11);
    background-color: #fff;
    overflow: hidden;

    .login-info {
      width: 70%;
      margin: 0 auto 20px;
      background: #f2f4f9;
    }

    .login-btn {
      width: 70%;
      height: 40px;
      margin: 50px auto 0;
      display: block;
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: #a5acb2;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    margin: 20px auto 60px;
    width: 80%;
    height: 44px;
    display: flex;
    align-items: baseline;
    justify-content: center;
    .title-container-left {
      width: 46px;
      height: 50px;
      margin-right: 15px;
    }
    .title-container-right {
      width: 70%;
      height: 22px;
    }
    img {
      width: 100%;
    }
    .title {
      font-size: 24px;
      color: #0064c8;
      padding: 20px 0 0;
      text-align: center;
      font-weight: bold;
      margin-top: 14px;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }

  .inputCodeBox {
    width: 100%;
    height: 47px;
    position: relative;
    display: flex;
    align-items: center;
  }

  .inputCodeBox > input {
    // flex: 1;
    width: calc(100% - 59px);
    height: 46px;
    padding: 0 10px;
    background: transparent;
    border: none;
    // color: #fff;
    box-sizing: border-box;
    font-size: 14px;
    outline: none;
    padding: 5px 42px;
    // margin-bottom: 22px;
  }

  .inputCodeBox > img {
    width: 138px;
    height: 46px;
    object-fit: contain;
    margin-left: 10px;
  }
}
</style>
